unit connection;

{$mode objfpc}{$H+}

interface

uses
  Classes,
  SysUtils,
  fpcunit,
  //testutils,
  testregistry,
  hadeconnectionmanager;

type

  { TTestHadeConnection }

  TTestHadeConnection = class(TTestCase)
  private
    Con: THadeConnection;
  protected
    procedure Setup; override;
    procedure TearDown; override;
  published
    procedure TestExecuteDirect;
    procedure TestTransaction;
  end;

implementation
uses
  hadebroker;

procedure TTestHadeConnection.Setup;
begin
  Con := THadeConnection.Create(SQLdb_SQLite,'test');
  Con.Database := 'test.s3db';
  con.Connect;
end;

procedure TTestHadeConnection.TearDown;
begin
  FreeAndNil(Con);
end;

{ TTestHadeConnection }
{ Every uses of method ExecuteDirect() need explicit Transaction call }
procedure TTestHadeConnection.TestExecuteDirect;
var
  sql: string;
begin
  sql := 'INSERT INTO person(first_name,last_name,age) VALUES(''Fajar'',''Khairil'',21)';
  con.StartTransaction;
  Try
    Con.ExecuteDirect(sql);
    con.commit;
  except
    on E:Exception do
    begin
      con.Rollback;
      fail('it should success! '+E.Message);
    end;
  end;
end;

procedure TTestHadeConnection.TestTransaction;
var
  sql,sql1: string;
begin
  sql := 'INSERT INTO person(first_name,last_name,age) VALUES(''Fajar'',''Khairil'',21)';
  sql1 := 'UPDATE persoyyn set first_name = ''Tokay'', last_name = ''Bau'' WHERE oid = 1 ';

  con.StartTransaction;
  Try
    Con.ExecuteDirect(sql);
    Con.ExecuteDirect(sql1);
    Con.Commit;
    fail('it should Rollback!');
  Except
    on E:Exception do
    begin
      Con.Rollback;
    end;
  end;
end;

initialization
  RegisterTest(TTestHadeConnection);
end.

